import { createRouter, createWebHashHistory, RouterView } from 'vue-router'
import store from '@/store'
import { h } from 'vue'


const Layout = () =>
    import ('@/views/Layout')
const Home = () =>
    import ('@/views/home/index')
const TopCategory = () =>
    import ('@/views/category/index')
const SubCategory = () =>
    import ('@/views/category/sub')
const Goods = () =>
    import ('@/views/goods/index')
const Login = () =>
    import ('@/views/login/index')
const LoginCallback = () =>
    import ('@/views/login/callback')
const Cart = () =>
    import ('@/views/cart/index')
const Checkout = () =>
    import ('@/views/member/pay/checkout')
const PayIndex = () =>
    import ('@/views/member/pay/index')
const PayResult = () =>
    import ('@/views/member/pay/result')

const MemberLayout = () =>
    import ('@/views/member/Layout')
const MemberHome = () =>
    import ('@/views/member/home')
const MemberOrder = () =>
    import ('@/views/member/order')
const MemberOrderDetail = () =>
    import ('@/views/member/order/detail')
const MemberHelp = () =>
    import ('@/views/member/help')
const MemberActive = () =>
    import ('@/views/member/active')


const routes = [{
        path: '/',
        component: Layout,
        children: [
            { path: '/', component: Home },
            { path: '/category/:id', component: TopCategory },
            { path: '/category/sub/:id', component: SubCategory },
            { path: '/product/:id', component: Goods },
            { path: '/cart', component: Cart },
            { path: '/member/checkout', component: Checkout },
            { path: '/member/pay', component: PayIndex },
            { path: '/pay/callback', component: PayResult },
            {
                path: '/member',
                component: MemberLayout,
                children: [
                    { path: '/member', component: MemberHome },
                    { path: '/member/help', component: MemberHelp },
                    { path: '/member/active', component: MemberActive },
                    { path: '/member/order', component: { render: () => h( < RouterView / > ) }, children: [{ path: '', component: MemberOrder }, { path: ':id', component: MemberOrderDetail }] }
                ]
            }
        ]
    },
    { path: '/login', component: Login },
    { path: '/login/callback', component: LoginCallback }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
    // 每次切换路由的时候滚到顶部
    scrollBehavior() {
        return { top: 0, left: 0 }
    }
})

router.beforeEach((to, from, next) => {
    // 前置导航守卫(可更改写法)
    // 用户信息
    const { token } = store.state.user.profile
        // 跳转去member开头的地址却没有登录
    if (to.path.startsWith('/member') && !token) {
        next({ path: '/login', query: { redirectUrl: to.fullPath } })
    }
    next()
})

export default router